<template>
  <view class="plan-list-container">
    <view class="header-section">
      <text class="page-title">健身计划</text>
    </view>
    
    <view class="toolbar-section">
      <button class="action-button" @click="showCreatePlanModal">创建计划</button>
    </view>
    
    <view class="plan-list">
      <view class="plan-item" v-for="plan in planList" :key="plan.id" @click="goToDetail(plan.id)">
        <view class="plan-info">
          <text class="plan-name">{{ plan.name }}</text>
          <text class="plan-goal">{{ plan.goal }}</text>
          <text class="plan-member">会员: {{ plan.memberName }}</text>
          <text class="plan-coach">教练: {{ plan.coachName }}</text>
          <text class="plan-date">{{ formatDate(plan.startDate) }} - {{ formatDate(plan.endDate) }}</text>
        </view>
        <view class="plan-status">
          <text class="status-tag" :class="getStatusClass(plan.status)">
            {{ getStatusText(plan.status) }}
          </text>
        </view>
        <view class="plan-actions">
          <button class="action-button small" @click.stop="editPlan(plan)">编辑</button>
          <button class="action-button small danger" @click.stop="deletePlan(plan)">删除</button>
        </view>
      </view>
    </view>
    
    <view class="pagination-section">
      <button class="pagination-button" :disabled="currentPage <= 1" @click="prevPage">上一页</button>
      <text class="page-info">第 {{ currentPage }} 页，共 {{ totalPages }} 页</text>
      <button class="pagination-button" :disabled="currentPage >= totalPages" @click="nextPage">下一页</button>
    </view>
    
    <view class="empty-state" v-if="planList.length === 0">
      <text class="empty-text">暂无健身计划</text>
    </view>
    
    <!-- 创建/编辑健身计划弹窗 -->
    <view class="modal" v-if="showPlanModal">
      <view class="modal-content large">
        <view class="modal-header">
          <text class="modal-title">{{ isEditPlan ? '编辑健身计划' : '创建健身计划' }}</text>
          <button class="close-button" @click="closePlanModal">×</button>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">计划名称</text>
            <input class="form-input" v-model="planForm.name" placeholder="请输入计划名称" />
          </view>
          <view class="form-item">
            <text class="form-label">训练目标</text>
            <input class="form-input" v-model="planForm.goal" placeholder="请输入训练目标" />
          </view>
          <view class="form-item">
            <text class="form-label">会员</text>
            <picker mode="selector" :range="memberOptions" @change="onMemberChange">
              <view class="form-input">{{ selectedMember || '请选择会员' }}</view>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">教练</text>
            <picker mode="selector" :range="coachOptions" @change="onCoachChange">
              <view class="form-input">{{ selectedCoach || '请选择教练' }}</view>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">开始日期</text>
            <picker mode="date" :value="planForm.startDate" @change="onStartDateChange">
              <view class="form-input">{{ planForm.startDate || '请选择开始日期' }}</view>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">结束日期</text>
            <picker mode="date" :value="planForm.endDate" @change="onEndDateChange">
              <view class="form-input">{{ planForm.endDate || '请选择结束日期' }}</view>
            </picker>
          </view>
          <view class="form-item">
            <text class="form-label">计划描述</text>
            <textarea class="form-textarea" v-model="planForm.description" placeholder="请输入计划描述"></textarea>
          </view>
          <view class="form-item">
            <text class="form-label">计划内容</text>
            <textarea class="form-textarea" v-model="planForm.content" placeholder="请输入计划内容"></textarea>
          </view>
          <view class="form-item" v-if="isEditPlan">
            <text class="form-label">状态</text>
            <picker mode="selector" :range="statusOptions" @change="onStatusChange">
              <view class="form-input">{{ selectedStatus || '请选择状态' }}</view>
            </picker>
          </view>
        </view>
        <view class="modal-footer">
          <button class="action-button cancel" @click="closePlanModal">取消</button>
          <button class="action-button" @click="savePlan">保存</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { planApi } from '../../src/services/plan'

// 定义健身计划类型
interface Plan {
  id: number
  memberId: number
  memberName: string
  coachId: number
  coachName: string
  name: string
  description: string
  goal: string
  content: string
  startDate: string
  endDate: string
  status: number
  createdAt: string
  updatedAt: string
}

// 健身计划列表
const planList = ref<Plan[]>([])

// 分页信息
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(1)
const totalPlans = ref(0)

// 是否显示健身计划弹窗
const showPlanModal = ref(false)

// 是否为编辑健身计划模式
const isEditPlan = ref(false)

// 当前编辑的健身计划
const currentPlan = ref<Plan>({ 
  id: 0,
  memberId: 0,
  memberName: '',
  coachId: 0,
  coachName: '',
  name: '',
  description: '',
  goal: '',
  content: '',
  startDate: '',
  endDate: '',
  status: 1,
  createdAt: '',
  updatedAt: ''
})

// 健身计划表单
const planForm = ref({
  memberId: 0,
  coachId: 0,
  name: '',
  description: '',
  goal: '',
  content: '',
  startDate: '',
  endDate: '',
  status: 1
})

// 会员选项
const memberOptions = ref<string[]>(['会员1', '会员2', '会员3'])
const memberList = ref<any[]>([])
const selectedMember = ref('')

// 教练选项
const coachOptions = ref<string[]>(['教练1', '教练2', '教练3'])
const coachList = ref<any[]>([])
const selectedCoach = ref('')

// 状态选项
const statusOptions = ['进行中', '已完成', '已取消']
const selectedStatus = ref('')

// 页面加载时获取健身计划列表
onMounted(() => {
  fetchPlanList()
})

// 获取健身计划列表
const fetchPlanList = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    const response: any = await planApi.getPlanList(params)
    planList.value = response.data.list || response.data
    totalPlans.value = response.data.total || planList.value.length
    totalPages.value = Math.ceil(totalPlans.value / pageSize.value)
    
    uni.showToast({
      title: '获取健身计划列表成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('获取健身计划列表失败:', error)
    uni.showToast({
      title: '获取健身计划列表失败',
      icon: 'none'
    })
  }
}

// 显示创建健身计划弹窗
const showCreatePlanModal = () => {
  isEditPlan.value = false
  planForm.value = { 
    memberId: 0,
    coachId: 0,
    name: '',
    description: '',
    goal: '',
    content: '',
    startDate: '',
    endDate: '',
    status: 1
  }
  selectedMember.value = ''
  selectedCoach.value = ''
  selectedStatus.value = ''
  showPlanModal.value = true
}

// 编辑健身计划
const editPlan = (plan: Plan) => {
  isEditPlan.value = true
  currentPlan.value = { ...plan }
  planForm.value = { ...plan }
  selectedMember.value = plan.memberName
  selectedCoach.value = plan.coachName
  selectedStatus.value = getStatusText(plan.status)
  showPlanModal.value = true
}

// 删除健身计划
const deletePlan = async (plan: Plan) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除健身计划 "${plan.name}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await planApi.deletePlan(plan.id)
          
          uni.showToast({
            title: '删除健身计划成功',
            icon: 'success'
          })
          
          // 重新获取健身计划列表
          fetchPlanList()
        } catch (error) {
          console.error('删除健身计划失败:', error)
          uni.showToast({
            title: '删除健身计划失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 跳转到健身计划详情页面
const goToDetail = (id: number) => {
  uni.navigateTo({
    url: `/pages/plan/detail?id=${id}`
  })
}

// 关闭健身计划弹窗
const closePlanModal = () => {
  showPlanModal.value = false
}

// 会员选择变化
const onMemberChange = (e: any) => {
  const selectedIndex = e.detail.value
  const selected = memberList.value[selectedIndex]
  planForm.value.memberId = selected.id
  selectedMember.value = selected.name
}

// 教练选择变化
const onCoachChange = (e: any) => {
  const selectedIndex = e.detail.value
  const selected = coachList.value[selectedIndex]
  planForm.value.coachId = selected.id
  selectedCoach.value = selected.name
}

// 开始日期变化
const onStartDateChange = (e: any) => {
  planForm.value.startDate = e.detail.value
}

// 结束日期变化
const onEndDateChange = (e: any) => {
  planForm.value.endDate = e.detail.value
}

// 状态选择变化
const onStatusChange = (e: any) => {
  const selectedIndex = e.detail.value
  selectedStatus.value = statusOptions[selectedIndex]
  planForm.value.status = selectedIndex + 1
}

// 格式化日期
const formatDate = (date: string) => {
  return date ? date.split('T')[0] : ''
}

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case 1: return '进行中'
    case 2: return '已完成'
    case 0: return '已取消'
    default: return '未知'
  }
}

// 获取状态样式类
const getStatusClass = (status: number) => {
  switch (status) {
    case 1: return 'status-active'
    case 2: return 'status-completed'
    case 0: return 'status-cancelled'
    default: return ''
  }
}

// 保存健身计划
const savePlan = async () => {
  // 表单验证
  if (!planForm.value.name) {
    uni.showToast({
      title: '请输入计划名称',
      icon: 'none'
    })
    return
  }
  
  if (!planForm.value.memberId) {
    uni.showToast({
      title: '请选择会员',
      icon: 'none'
    })
    return
  }
  
  if (!planForm.value.coachId) {
    uni.showToast({
      title: '请选择教练',
      icon: 'none'
    })
    return
  }
  
  if (!planForm.value.startDate) {
    uni.showToast({
      title: '请选择开始日期',
      icon: 'none'
    })
    return
  }
  
  if (!planForm.value.endDate) {
    uni.showToast({
      title: '请选择结束日期',
      icon: 'none'
    })
    return
  }
  
  try {
    if (isEditPlan.value && currentPlan.value.id) {
      // 编辑健身计划
      await planApi.updatePlan(currentPlan.value.id, planForm.value)
      
      uni.showToast({
        title: '更新健身计划成功',
        icon: 'success'
      })
    } else {
      // 创建健身计划
      await planApi.createPlan(planForm.value)
      
      uni.showToast({
        title: '创建健身计划成功',
        icon: 'success'
      })
    }
    
    // 关闭弹窗
    closePlanModal()
    
    // 重新获取健身计划列表
    fetchPlanList()
  } catch (error) {
    console.error('保存健身计划失败:', error)
    uni.showToast({
      title: '保存健身计划失败',
      icon: 'none'
    })
  }
}

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchPlanList()
  }
}

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchPlanList()
  }
}
</script>

<style lang="scss" scoped>
.plan-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.header-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
  }
}

.toolbar-section {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  text-align: right;
}

.action-button {
  background-color: #4B0082;
  color: #fff;
  border: none;
  padding: 15rpx 30rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  
  &.small {
    padding: 10rpx 20rpx;
    font-size: 24rpx;
  }
  
  &.danger {
    background-color: #f44336;
  }
  
  &.cancel {
    background-color: #999;
  }
}

.plan-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.plan-item {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.plan-info {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.plan-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.plan-goal {
  font-size: 28rpx;
  color: #4B0082;
}

.plan-member, .plan-coach {
  font-size: 24rpx;
  color: #666;
}

.plan-date {
  font-size: 24rpx;
  color: #2196F3;
}

.plan-status {
  margin-bottom: 20rpx;
}

.status-tag {
  font-size: 24rpx;
  padding: 5rpx 15rpx;
  border-radius: 20rpx;
}

.status-active {
  background-color: #e8f5e9;
  color: #4caf50;
}

.status-completed {
  background-color: #e3f2fd;
  color: #2196f3;
}

.status-cancelled {
  background-color: #ffebee;
  color: #f44336;
}

.plan-actions {
  display: flex;
  gap: 10rpx;
  justify-content: flex-end;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30rpx;
  padding: 0 20rpx;
}

.pagination-button {
  background-color: #4B0082;
  color: #fff;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.pagination-button[disabled] {
  background-color: #ccc;
}

.page-info {
  font-size: 28rpx;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 10rpx;
  width: 90%;
  max-width: 600rpx;
  
  &.large {
    max-width: 800rpx;
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-button {
  background: none;
  border: none;
  font-size: 40rpx;
  color: #999;
  padding: 0;
  width: 50rpx;
  height: 50rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.form-input {
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  width: 100%;
  box-sizing: border-box;
}

.form-textarea {
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  width: 100%;
  height: 150rpx;
  box-sizing: border-box;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 2rpx solid #f5f5f5;
}
</style>